package webs.servlet.ServletSession;

//使用Session来进行登陆验证
import webs.servlet.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;

@WebServlet("/sessionDemo4")
public class sessionDemo4 extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkPassword = req.getParameter("checkPassword");
        HttpSession session = req.getSession();
        String checkCode_session = (String)session.getAttribute("checkCode_session");
        //验证码只用一次，获取成功后移除session
        session.removeAttribute("checkCode_session");
        if(checkCode_session!=null && checkPassword.equals(checkCode_session))
        {
            //连接数据库，检验用户名和密码，使用JDBC Template
            Connection connection = null;
            try
            {
                connection = DruidToolClass.getConnection();
                String sql="select username,password from user where username= ? and password= ?";
                PreparedStatement sta = connection.prepareStatement(sql);
                sta.setString(1,username);
                sta.setString(2,password);
                ResultSet resultSet = sta.executeQuery();
                User loginUser = new User();
                while (resultSet.next())
                {
                    loginUser.setUsername(resultSet.getString(1));
                    loginUser.setPassword(resultSet.getString(2));
                }
                if(loginUser.getUsername()!=null)
                {
                    //要重定向到success.jsp，故需要将数据存储到session中
                    session.setAttribute("username", loginUser.getUsername());
                    resp.sendRedirect(req.getContextPath() + "/success.jsp");
                }
                else
                {
                    //登陆失败，用户名或密码错误，跳转到Login.jsp
                    req.setAttribute("up_error","用户名或密码错误");
                    req.getRequestDispatcher("/login.jsp").forward(req,resp);
                }
                sta.close();
                connection.close();
            } catch (SQLException throwables)
            {

                throwables.printStackTrace();
            }
        }
        else
        {
            //登陆失败，验证码错误，跳转到Login.jsp
            req.setAttribute("co_error","验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req,resp);
    }
}
